package dao_base

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_base"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetArticleLabelPageList(baseArticleLabel model_base.SelectBaseArticleLabel) (baseArticleLabels []model_base.BaseArticleLabelVo, total int64, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleLabelPo{})
	if baseArticleLabel.UserId != 0 {
		db = db.Where("user_id = ?", baseArticleLabel.UserId)
	}
	if baseArticleLabel.LabelName != "" {
		db = db.Where("label_name like ?", "%"+baseArticleLabel.LabelName+"%")
	}
	if baseArticleLabel.Status != "" {
		db = db.Where("status = ?", baseArticleLabel.Status)
	}
	if !baseArticleLabel.StartTime.IsZero() {
		db = db.Where("create_time >= ?", baseArticleLabel.StartTime)
	}
	if !baseArticleLabel.EndTime.IsZero() {
		db = db.Where("create_time <= ?", baseArticleLabel.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("create_time desc")
	if baseArticleLabel.PageNum != nil && baseArticleLabel.PageSize != nil {
		db = db.Limit(*baseArticleLabel.PageSize).Offset((*baseArticleLabel.PageNum - 1) * *baseArticleLabel.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&baseArticleLabels).Error
	err = errs.ErrNotFound(err)
	return
}

func GetArticleLabelInfo(labelId int) (baseArticleLabel model_base.BaseArticleLabelVo, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleLabelPo{})
	err = db.Where("label_id = ? and deleted = '0'", labelId).First(&baseArticleLabel).Error
	err = errs.ErrNotFound(err)
	return
}

func AddArticleLabel(baseArticleLabel model_base.BaseArticleLabelPo) (int, error) {
	db := mysql.Db("salve-1")
	res := db.Create(&baseArticleLabel)
	return baseArticleLabel.LabelId, errs.ErrNotFound(res.Error)
}

func EditArticleLabel(baseArticleLabel model_base.BaseArticleLabelPo) (int64, error) {
	db := mysql.Db("salve-1")
	res := db.Updates(&baseArticleLabel)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveArticleLabel(labelIds []string, uk string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleLabelPo{})
	db.Where("label_id in (?)", labelIds)
	res := db.Updates(&model_base.BaseArticleLabelPo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeletedArticleLabel(labelIds []string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticleLabelPo{})
	db.Where("label_id in (?)", labelIds)
	res := db.Delete(&model_base.BaseArticleLabelPo{})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
